import { ChatContext } from '@/app/chat-context';
import { CopyOutlined, DownOutlined, UpOutlined  } from '@ant-design/icons';
import WorkbenchesIcon from '@/components/workbenches/icons';
import { Button, message, Popover,Flex,Space } from 'antd';
import copy from 'copy-to-clipboard';
import { CSSProperties, useContext, useState,useRef } from 'react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { coldarkDark, oneDark,oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { WorkbenchesContext, } from '@/components/workbenches/workbenches-context';

interface Props {
  code: string;
  language: string;
  customStyle?: CSSProperties;
  light?: { [key: string]: CSSProperties };
  dark?: { [key: string]: CSSProperties };
}

export function CodePreview({ code, light, dark, language, customStyle }: Props) {
  // console.log('code', code);
  // console.log('language', language,code.length);
  
  const { mode } = useContext(ChatContext);
  const [expanded, setExpanded] = useState(true);
  const contentRef = useRef<HTMLDivElement>(null);
  // 代码块最大高度（收起时）
  const COLLAPSED_HEIGHT = 80;

  const { setCurrentItemChange } = useContext(WorkbenchesContext);
  const from = localStorage.getItem('CHAT_FROM') || 'chat'; // 默认来自 智能对话 
  const copilotType = localStorage.getItem('COPILOT_TYPE') || '';

  // 如果是 JSON 代码块，先存上
  if (from === 'copilot' && language === 'json') {
      localStorage.setItem('jsonCode', code); // 存储到 localStorage
  }

 // 执行按钮的处理函数
 const handleExecute = () => {
  let jsonObject = null; 
  const jsonCode = localStorage.getItem('jsonCode');
  const cleanedJsonString = jsonCode
  .replace(/[\n\r]/g, '')
  .replace(/\s+/g, ' ')
  .trim();

  if(cleanedJsonString === 'undefined'){
    message.warning('执行错误，没有生成模型数据')
  }else{
    jsonObject = JSON.parse(cleanedJsonString);
  
    if (jsonObject) {
      setCurrentItemChange(jsonObject);
    }
  }
 };

  return (
    <div className='relative' style={{ display: from === 'copilot' && language === 'json' ? 'none' : 'block' }}>
      <Flex className="h-10 items-center justify-between px-2 bg-gray-100 dark:bg-gray-800 rounded-tl-md rounded-tr-md" style={{marginBottom: '-7px'}}>
        <Space>
          <div className='text-sm'>
            {language}
          </div>
          { code.length >= 100 && <Button           
            type='text'
            icon={expanded ? <UpOutlined /> : <DownOutlined />}
            onClick={() => setExpanded(e => !e)}
          /> }
          
        </Space> 
        <div className='flex items-center'>        
          {from == 'copilot' && copilotType === 'MODEL_INDEX' &&
            <Popover content='执行' trigger="hover">
              <Button className="pr-2 pl-2"           
                type='text'
                onClick={handleExecute}          
              >
                <WorkbenchesIcon type="模型" />
              </Button>
            </Popover>
          }
          <Button         
            type='text'
            icon={<CopyOutlined />}
            onClick={() => {
              const success = copy(code);
              message[success ? 'success' : 'error'](success ? '复制成功' : '复制失败');
            }}
          />
        </div>
      </Flex> 

      {/* 代码块 */}
      <div
        ref={contentRef}
        style={{
          maxHeight: expanded ? (contentRef.current?.scrollHeight ?? 'none') : COLLAPSED_HEIGHT,
          overflow: 'hidden',
          transition: 'max-height 0.3s cubic-bezier(0.4,0,0.2,1)',
        }}
      >
        <SyntaxHighlighter
          customStyle={customStyle}
          language={language}
          style={mode === 'dark' ? (dark ?? coldarkDark) : (light ?? oneLight)}
        >
          {code}
        </SyntaxHighlighter>
      </div>

      {/* 展开时不显示遮罩，收起且内容超出时显示渐变遮罩 */}
      {!expanded && (contentRef.current?.scrollHeight ?? 0) > COLLAPSED_HEIGHT && (
        <div
          style={{
            position: 'absolute',
            left: 0,
            right: 0,
            bottom: 0,
            height: 40,
            pointerEvents: 'none',
            background: 'linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,0.8) 80%)',
          }}
          className="dark:bg-gradient-to-b dark:from-transparent dark:to-[#232734cc]"
        />
      )}

    </div>
  );
}
